package main

import (
	"fmt"
	"zinx/Zinx/ziface"
	"zinx/Zinx/znet"
)

// id=0路由处理业务方法
type hiRouter struct {
	znet.BaseRouter
}

func (r *hiRouter) Handle(request ziface.IRequest) {
	fmt.Printf("[Msg]ID: %d,Data: %s\n", request.GetID(), request.GetData())
	err := request.GetConnection().SendMsg(0, []byte("hi,ok"))
	if err != nil {
		fmt.Println("[Handle]err:", err)
		return
	}
}

// id=1路由处理业务方法
type hellowRouter struct {
	znet.BaseRouter
}

func (r *hellowRouter) Handle(request ziface.IRequest) {
	fmt.Printf("[Msg]ID: %d,Data: %s\n", request.GetID(), request.GetData())
	err := request.GetConnection().SendMsg(1, []byte("hellow,ok"))
	if err != nil {
		fmt.Println("[Handle]err:", err)
		return
	}
}

// 启动连接后的Hook
func doOnConnStart(conn ziface.IConnection) {
	fmt.Printf("[Conn]ID: %d is Connecting\n", conn.GetConnID())
	if err := conn.SendMsg(202, []byte("OnConnStart..")); err != nil {
		fmt.Println(err)
	}
	conn.SetProperty("Name", "axinzi")
	conn.SetProperty("Gitee", "https://gitee.com/axinzi")
	conn.SetProperty("GitHub", "https://github.com/axinzi")
}

// 关闭连接前的Hook
func doOnConnStop(conn ziface.IConnection) {
	fmt.Printf("[Conn]ID: %d is Lost\n", conn.GetConnID())
	if name, err := conn.GetProperty("Name"); err == nil {
		fmt.Println("Name: ", name)
	}
	if gitee, err := conn.GetProperty("Gitee"); err == nil {
		fmt.Println("Gitee: ", gitee)
	}
	if github, err := conn.GetProperty("GitHub"); err == nil {
		fmt.Println("GitHub: ", github)
	}
}

func main() {
	// 创建服务器
	s := znet.NewServer()
	// 注册钩子
	s.SetOnConnStart(doOnConnStart)
	s.SetOnConnStop(doOnConnStop)
	// 添加路由
	s.AddRouter(0, &hiRouter{})
	s.AddRouter(1, &hellowRouter{})
	// 运行服务器
	s.Server()
}
